<template>
  <div class="business-item-form-configure w-full h-full display-flex-column" style="overflow: hidden">
    <div class="btn-box display-flex" style="justify-content: flex-start">
      <a-button type="primary" class="m-r-sm" @click="handlerCreateFormItem">新建</a-button>
      <a-button type="primary m-r-sm" @click="loadData">刷新</a-button>
      <div class="btn-selector display-flex m-r-sm">
        <div class="selector-name m-r-xs">环境变量:</div>
        <a-select v-model="selectInvSource" class="selector-item" style="width: 150px" @change="handlerInvSourceChange">
          <a-select-option value="investment_three_new">
            新版表单配置
          </a-select-option>
          <a-select-option value="investment_three_old">
            旧版表单配置
          </a-select-option>
        </a-select>
      </div>
      <div class="btn-selector display-flex">
        <div class="selector-name m-r-xs">流程类型:</div>
        <a-select v-model="selectCategory" class="selector-item" style="width: 150px" @change="handlerInvCategoryChange">
          <a-select-option value="common">
            通用流程
          </a-select-option>
          <a-select-option value="ext">
            延期/变更
          </a-select-option>
          <a-select-option value="des">
            注销
          </a-select-option>
        </a-select>
      </div>
      <div class="h-full flex-1"></div>
      <div class="btn-right-box display-flex" style="justify-content: flex-start">
        <div class="btn-selector display-flex m-r-sm">
          <div class="selector-name m-r-xs">业务类型:</div>
          <a-select v-model="selectBusinessType" class="selector-item" style="width: 300px" @change="handlerBusinessTypeChange">
            <a-select-option v-for="item in businessTypeList" :key="item.id" :value="item.id">
              {{ `${item.item_name}(${item.businessName})` }}
            </a-select-option>
          </a-select>
        </div>
      </div>
    </div>
    <div class="w-full" style="height: 10px"></div>
    <div class="w-full display-flex" style="justify-content: flex-start" v-if="selectBusinessTypeObj" >
      <div class="btn-selector display-flex m-r-sm" style="justify-content: flex-start">
        <div class="selector-name m-r-xs">3.0业务名:</div>
        <div class="selector-name m-r-xs">{{ selectBusinessTypeObj.item_name }}</div>
      </div>
      <div class="btn-selector display-flex m-r-sm" style="justify-content: flex-start">
        <div class="selector-name m-r-xs">3.0事项编码:</div>
        <div class="selector-name m-r-xs">{{ selectBusinessTypeObj.item_code }}</div>
      </div>
    </div>
    <div class="w-full" style="height: 10px"></div>
    <div class="table-box flex-1" style="overflow: hidden">
      <a-table
        class="dist-box-table"
        bordered
        :rowClassName="setRowClassName"
        :customRow="customRow"
        :loading="table.loading"
        :rowKey="(record, index)=>index"
        :columns="table.columns"
        :data-source="table.dataSource"
        :pagination="table.pagination"
        :scroll="{ x: false, y: 'calc(100% - 70px)' }"
      >
        <template slot="index" slot-scope="text,record,index">
          <div>{{ index + 1 }}</div>
        </template>
        <span slot="operate" slot-scope="text,record">
          <div class="display-flex">
            <a-button type="default" @click="handlerEditRecord(record)">
              编辑
            </a-button>
            <a-button class="m-l-md" type="danger" @click="handlerRemoveRecord(record)">
              删除
            </a-button>
          </div>
        </span>
      </a-table>
    </div>
  </div>
</template>
<script>
import PageInitFn from '@/api/pageInitFn'
import dapProjectService from '@/api/dapProjectService'

export default {
  name: 'BusinessItemFormConfigure',
  props: {},
  data () {
    return {
      table: {
        columns: [],
        dataSource: [],
        loading: false,
        rowSelection: {
          selectedRowKeys: [],
          selectedRows: [],
          onChange: (selectedRowKeys, selectedRows) => {
            this.table.rowSelection.selectedRowKeys = selectedRowKeys
            this.table.rowSelection.selectedRows = selectedRows
          }
        },
        pagination: {
          pageSize: 200, // 默认每页显示数量
          total: 0,
          current: 1,
          showSizeChanger: true, // 显示可改变每页数量
          pageSizeOptions: ['10', '20', '50', '100', '200', '500'], // 每页数量选项
          showTotal: (total) => `共${total}条数据`, // 显示总数
          onShowSizeChange: (current, pageSize) => {
            this.filter.pageIndex = 1
            this.filter.pageSize = pageSize
            this.table.pagination.pageSize = pageSize
            this.loadData(this.filterText)
          },
          onChange: (current, pageSize) => {
            this.filter.pageIndex = current
            this.filter.pageSize = pageSize
            this.table.pagination.current = current
            this.table.pagination.pageSize = pageSize
            this.loadData(this.filterText)
          }
        }
      },
      filter: {
        pageIndex: 1,
        pageSize: 200
      },
      selectInvSource: '',
      businessTypeList: [],
      selectBusinessType: '',
      selectCategory: ''
    }
  },
  created () {
    this.pageInitFn = new PageInitFn(this)
    this.pageInitFn.created()
  },

  async mounted () {
    this.initInvSource()
    this.initInvCategory()
    await this.getInvBusinessItem()
    this.pageInitFn.mounted()
    this.Event.$on('_REFRESH_TODO_BOX_', this.loadData)
  },
  computed: {
    selectBusinessTypeObj () {
      return this.getSelectBusinessTypeObj()
    }
  },
  methods: {
    handlerCreateFormItem (sourceId) {
      const that = this
      const props = {
        businessType: this.selectBusinessTypeObj,
        category: this.selectCategory
      }
      if (sourceId) {
        props.sourceId = Number(sourceId)
      }

      this.$dialog({
        title: sourceId ? '修改字段映射' : '新建字段映射',
        content: () => import('./details/form/FormEditDialog.vue'),
        width: window.document.body.clientWidth * 0.8 + 'px',
        bodyStyle: { height: '700px', padding: '0' },
        centered: true,
        maskClosable: false,
        okButtonProps: {},
        props: props,
        model: {
        },
        on: {
          async ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            const result = dialogCtl.getSaveData()
            if (!result.state) {
              return
            }
            const params = result.data
            await dapProjectService.saveBusinessItemFormList([params]).then(res => {
              if (res.length > 0 && res[0]) {
                that.$message.success('保存成功')
                that.loadData()
                ctl.closeDialog()
              } else {
                that.$message.error('保存失败,可能存在数据冲突')
              }
            })
          }
        }
      })
    },
    handlerBusinessTypeChange (data) {
      this.loadData()
    },
    getSelectBusinessTypeObj () {
      if (!this.selectBusinessType) {
        return null
      } else {
        const obj = this._.find(this.businessTypeList, item => item.id === this.selectBusinessType)
        return obj
      }
    },
    async getInvBusinessItem () {
      const oldBusiness = this._.cloneDeep(this.selectBusinessTypeObj)
      const source = this.selectInvSource
      const data = await dapProjectService.listBusinessItemBySource(source)
      this.businessTypeList = data
      if (!this.selectBusinessType) {
        if (!data || data.length < 0) {
          this.$message.warning('未获取到业务类型配置')
        } else {
          this.selectBusinessType = data[0].id
        }
      } else {
        let target = this._.find(this.businessTypeList, item => item.id === this.selectBusinessType)
        if (!target) {
          target = this._.find(this.businessTypeList, item => item.item_code === oldBusiness.item_code)
        }
        if (target) {
          this.selectBusinessType = target.id
        } else {
          this.selectBusinessType = ''
        }
      }
    },
    handlerInvCategoryChange (data) {
      this.selectCategory = data
      localStorage.setItem('invCategory', data)
      this.loadData()
    },
    async handlerInvSourceChange (data) {
      this.selectInvSource = data
      localStorage.setItem('invSource', data)
      await this.getInvBusinessItem()
      this.loadData()
    },
    initInvSource () {
      const invSource = localStorage.getItem('invSource')
      if (!invSource) {
        this.selectInvSource = 'investment_three_new'
      } else {
        this.selectInvSource = invSource
      }
    },
    initInvCategory () {
      const category = localStorage.getItem('invCategory')
      if (!category) {
        this.selectCategory = 'common'
      } else {
        this.selectCategory = category
      }
    },
    handlerEditRecord (record) {
      this.handlerCreateFormItem(record.ID)
    },
    handlerRemoveRecord (record) {
      this.$confirm({
        title: '提示',
        content: '确认执行删除操作，删除后项目不可恢复！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          dapProjectService.deleteBusinessItemForm({ id: record.ID }).then((d) => {
            this.loadData()
          })
        }
      })
    },
    setRowClassName (record, index) {
      return this.pageInitFn.setRowClassName(record, 'ID')
    },
    customRow (record, index, key) {
      // record.key = key
      return this.pageInitFn.customRow(record, 'ID')
    },
    async loadData (filterText = null) {
      const businessMap = this.getSelectBusinessTypeObj()
      let itemFilter = null
      if (businessMap) {
        itemFilter = businessMap.item_code
      }
      console.log('businessMap', businessMap)
      // console.log(this.$route.meta)
      this.filterText = filterText || null
      await this.pageInitFn.loadData({
        itemFilter: itemFilter,
        dataMode: this.selectInvSource,
        category: this.selectCategory,
        itemName: this.selectBusinessTypeObj.item_name
      })
    }
  }
}
</script>

<style scoped lang="less">
.business-item-form-configure {
  background-color: white;
  padding: 10px;
}
</style>
